<template>
  <el-drawer
    v-if="visible"
    title="大车用户详情"
    :visible.sync="visible"
    :with-header="true"
    direction="rtl"
    :wrapper-closable="true"
    :append-to-body="true"
    class="cartDriverDetail"
  >
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      class="table"
      border
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      :immediate-fetch="false"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <csm-detail
      ref="csmDetail"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
    />
  </el-drawer>
</template>

<script>
  import {
    queryMap,
    queryBindcsmDriverList
  } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import CsmDetail from '@/views/components/CsmDetailModal/index.vue'
  export default {
    name: '',
    components: {
      CsmDetail
    },
    data() {
      return {
        treeData: [],
        calcTypeList: [], // 收款方式枚举
        paymenFilList: [], // 付款方
        customerTypeMap: [],
        visible: false,
        depositTypeMap: [
          { desc: '50型押金用户', value: 1 },
          { desc: '非50型押金用户', value: 2 },
          { desc: '无押金用户', value: 3 },
          { desc: '混合型押金用户', value: 4 }
        ],
        qtype: null,
        query: {
          orgSNNo: null,
          csmType: null,
          depositType: null,
          param: ''
        },
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            align: 'center'
          },
          { label: '绑定司机编号',
            prop: 'driverCode'
          },
          {
            label: '绑定司机',
            prop: 'driverName'

          },
          {
            label: '司机所属机构',
            prop: 'orgName',
            showOverflowTooltip: true
          },
          {
            label: '用户编号',
            prop: 'csmCode',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openCsmDetail(row)}>{row.csmCode}</el-link>
          )
          },
          {
            label: '用户姓名',
            prop: 'csmName',
            showOverflowTooltip: true
          },
          {
            label: '用户电话',
            prop: 'csmPhone',
            width: 110
          },
          {
            label: '联系地址',
            prop: 'csmAddress',
            showOverflowTooltip: true
          },
          {
            label: '用户所属机构',
            prop: 'csmOrgName',
            showOverflowTooltip: true
          },
          {
            label: '用户类型',
            prop: 'csmType',
            showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.csmType && formatColumnMap(this.customerTypeMap, 'value', Number(row.csmType), 'desc') }</span>
          },
          {
            label: '用户押金类型',
            prop: 'depositType',
            showOverflowTooltip: true,
            render: (h, { row }) => <span>{ row.depositType && formatColumnMap(this.depositTypeMap, 'value', row.depositType, 'desc') }</span>
          },
          {
            label: '值班司机编号',
            prop: 'dutyDriverCode'
          },
          {
            label: '值班司机',
            prop: 'dutyDriverName',
            showOverflowTooltip: true,
            render: (h, { row }) => (
              row.dutyDriverName ? <span style = { !row.orderReceiver ? 'color:#04CDC1' : ''}>{!row.orderReceiver ? `${row.dutyDriverName}（接单）` : `${row.dutyDriverName}`}</span> : <span></span>
            )
          },
          {
            label: '值班押运员编号',
            prop: 'escortCode'
          },
          {
            label: '值班押运员',
            prop: 'escortName',
            showOverflowTooltip: true,
            render: (h, { row }) => (
              row.escortName ? <span style = { row.orderReceiver ? 'color:#04CDC1' : ''}>{row.orderReceiver ? `${row.escortName}（接单）` : `${row.escortName}`}</span> : <span></span>
            )
          }
        ]
      }
    },
    async created() {
    },
    mounted() {
    },
    beforeDestroy() {
    },
    methods: {
      open(temp, type) {
        return new Promise(resolve => {
          this.resolve = resolve
          if (temp) {
            this.query.depositType = type
            this.query.driverCode = temp.driverCode
            this.getTreeData()
            this.queryOptionsMap()
            this.fetchData({ currentPage: 1, pageSize: 20 })
          }
          this.visible = true
        })
      },
      // 查询字典枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })
        ])
        this.calcTypeList = res1.data // 收款方式
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        res2.data.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
        this.customerTypeMap = res3.data // 客户类型
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.query.param !== '') {
          query[this.qtype] = this.query.param
        }
        const res = await queryBindcsmDriverList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 打开详情
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row, true)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        // if (row.orderStatus === 7) {
        //   return 'danger-row'
        // }
        // return ''
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.cartDriverDetail {
  /deep/.el-drawer {
    width: 75% !important;
  }
}
.table {
  padding: 0 20px;
}
</style>
